package com.training.admin.web.controller.report;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.dynamic.report.DynamicReport;
import com.training.admin.entity.search.DynamicReportSearch;
import com.training.admin.entity.upload.UploadResult;
import com.training.admin.service.DynamicReportService;
import com.training.admin.service.ReportService;
import com.training.admin.web.controller.view.DynamicReportExportExcelView;

/**
 * 
 * @author Rockett
 * 
 */
@Controller
@MenuSetting("menu-report")
public class DynamicReportController {
	private static final Logger logger = LoggerFactory.getLogger(DynamicReportController.class);
  
    @Autowired
    private DynamicReportService dynamicReportService;
   
    @Autowired
    private ReportService reportService;

	
	/**
     * 自定义报表主页
     * @return
     */
    @SuppressWarnings("unused")
    @RequestMapping(value = "/dynamic-report", method = RequestMethod.GET)
    @MenuSetting("submenu-dynamic-report")
    public ModelAndView dynamicReportSearch(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("dynamic-report/dynamic-report-search");
        modelAndView = doInitForDymanicReport(request,modelAndView );
        String currentReport = request.getParameter("reportId");
        
        return modelAndView;
    }
	/**
     * 自定义报表主页
     * @return
     */
    @RequestMapping(value = "/dynamic-report", method = RequestMethod.GET , params = "filter")
    @MenuSetting("submenu-dynamic-report")
    @SuppressWarnings("rawtypes")
    public ModelAndView onDynamicReportSearch(HttpServletRequest request,DynamicReportSearch dynamicReportSearch,Page page)  {
        ModelAndView modelAndView = new ModelAndView("dynamic-report/dynamic-report");
        modelAndView = doInitForDymanicReport(request,modelAndView );
        int totals =reportService.count(dynamicReportSearch);
        if(totals > 0){
        	//List<ProjectReport> projectReports = new ArrayList<ProjectReport>();
            
            List reportList = reportService.search(dynamicReportSearch, page.with(totals));
            modelAndView.addObject("dynamicReports", reportList);
            modelAndView.addObject("recordCount", reportList.size());
            modelAndView.addObject("page", page);
            
        }
		
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
        
        return modelAndView;
    }
    
    /**
     * 上传报表
     * 
     * @return
     */
    @SuppressWarnings("unused")
    @RequestMapping(value = "/dynamic-report/report-upload", method = RequestMethod.POST)
    public ModelAndView onUpload(HttpServletRequest request,@RequestParam("file") MultipartFile file,
			RedirectAttributes attributes) {
        ModelAndView modelAndView = new ModelAndView("redirect:/dynamic-report");
        //modelAndView = doInitForDymanicReport(request,modelAndView );
        // 1. get upload result
        DynamicReport dynamicReport = new DynamicReport();
        String reportName = request.getParameter("name");
        if (!StringUtil.isBlank(reportName)){
        	//check reportName Exists
            List<DynamicReport> dynamicReportListForCheck = dynamicReportService.listByName(reportName);
            if(dynamicReportListForCheck!=null && dynamicReportListForCheck.size()>0){
            	//error
            	logger.error("report name already Exists!");
            	modelAndView.addObject("errorMessage","Report name already Exists!");
            	return modelAndView;
            }

        	dynamicReport.setName(reportName);
            dynamicReportService.save(dynamicReport);
            List<DynamicReport> dynamicReportList = dynamicReportService.listByName(reportName);
            if(dynamicReportList!=null && dynamicReportList.size()>0){
            	dynamicReport=dynamicReportList.get(0);
            }
           
            List<UploadResult> traineeUploadResults = dynamicReportService.upload( file,dynamicReport);
           
            
            // 2. set to redirectAttributes
            //attributes.addAttribute("driverUploadResults", JsonUtils.toJson(driverUploadResults));
            modelAndView.addObject("reportId",dynamicReport.getId());
        }
        
        return modelAndView;
    }
    /**
     * 上传新报表
     * 
     * @return
     */
    @RequestMapping(value = "/dynamic-report/report-upload", method = RequestMethod.GET)
    public ModelAndView upload(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("dynamic-report/report-upload");
        modelAndView = doInitForDymanicReport(request,modelAndView );

        
        return modelAndView;
    }

    /**
     * 报表 - 导出
     * 
     * @param search
     * @return
     */
    @RequestMapping(value = "/dynamic-report-export", method = RequestMethod.GET)
    public ModelAndView onDynamicReportExport(HttpServletRequest request) {
        
        String currentReport = request.getParameter("reportId");

        if(StringUtil.isBlank(currentReport)){
        	//error parameter
        	logger.error("report id is null!");
        	return null;
        }
    	
        DynamicReport dynamicReport = dynamicReportService.load(DynamicReport.class, new Long(currentReport));
        
        String path= dynamicReport.getFullFilePath();
        String fileName= dynamicReport.getFileName();
        
        ModelAndView modelAndView = new ModelAndView(new DynamicReportExportExcelView(path,fileName, fileName));
               
        
        return modelAndView;
        
    }
    
    /**
     * commont function
     * @param request
     * @param modelAndView
     * @return
     */
    private ModelAndView doInitForDymanicReport(HttpServletRequest request,ModelAndView modelAndView){
        String currentReport = request.getParameter("reportId");
        if(StringUtils.isBlank(currentReport)|| currentReport.equals("-1")){
        	//default
        	currentReport="-1";
        }else{
        	DynamicReport dynamicReport = dynamicReportService.load(DynamicReport.class, new Long(currentReport));
        	String columnString=dynamicReport.getColumns();
        	if (!StringUtil.isBlank(columnString)){
        		String[] cols = columnString.split(",");
               	modelAndView.addObject("columns", cols);
               	modelAndView.addObject("columnCount", cols.length);
        	}
        	modelAndView.addObject("dynamicReport", dynamicReport);
        }
        
        List<DynamicReport> reports = dynamicReportService.listAll(DynamicReport.class);
                
        modelAndView.addObject("reports", reports);
        modelAndView.addObject("reportId", currentReport);
        return modelAndView;
    }
}
